package com.changgou.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author ：hushengjin
 */

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    //用户请求参数|头文件|Cookie中令牌参数名字
    private static final String AUTHORIZE_TOKEN = "Authorization";

    private static final String USER_LOGIN_URL = "http://localhost:9001/oauth/login";

    /**
     * 全局拦截
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求路径
        String path = request.getURI().getPath();
        //判断是否为登录请求
        if (path.startsWith("/api/user/login") || path.startsWith("/api/brand/search/")) {
            //放行
            return chain.filter(exchange);
        }
        //获取头文件中的令牌信息
        String token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);
        //如果头文件没有,从请求参数中获取
        if (StringUtils.isEmpty(token)) {
            token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
        }
        //如果请求参数中没有,则从cookie中获取
        if (StringUtils.isEmpty(token)) {
            HttpCookie cookie = request.getCookies().getFirst(AUTHORIZE_TOKEN);
            if (cookie != null) {
                token = cookie.getValue();
            }
        }
        if (StringUtils.isEmpty(token)) {
            //上述都没有,拦截
            response.setStatusCode(HttpStatus.SEE_OTHER);
            //将访问路径已请求头的参数形式传递回去
            response.getHeaders().set("location", USER_LOGIN_URL + "?FROM=" + request.getURI());
            return response.setComplete();
        }
        //开始鉴权
        try {
            //JwtUtil.parseJWT(token);
            //将令牌书据添加到请求头
            request.mutate().header(AUTHORIZE_TOKEN, "bearer " + token);
        } catch (Exception e) {
            //设置错误状态吗
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * 拦截器执行顺序
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
